//
//  MallBookViewController.m
//  LiteraryTune
//
//  Created by 神州四达 on 2018/1/18.
//  Copyright © 2018年 cxd. All rights reserved.
//  图书

#import "MallBookViewController.h"
#import "BookCollectCell.h"
#import "FooterCollectionReusableView.h"
#import "MallBookHeaderCollectionReusableView.h"
#import "ClassifyCircleCollectionViewCell.h"
#import "CateCenterCollectionReusableView.h"
#import "BookDetailShowViewController.h"
#import "BookTypeSearchView.h"
#import "ClassifyModel.h"
#import "BookClassifyCollectionCell.h"
#import "BookSearchVC.h"
#import "BookMoreVC.h"
#import "BookCateVC.h"
#import "BookListPageModel.h"
#import "XYClassifyModel.h"
#import "ClassifyHeaderView.h"

@interface MallBookViewController () <UICollectionViewDelegate,UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, ClassifyHeaderViewDelegate>

@property (nonatomic, strong)UIButton *searchBtn;
@property (nonatomic, strong)BookTypeSearchView *searchView;
@property (nonatomic, strong)UICollectionView *showCollectionView;
@property (nonatomic, strong)UICollectionView *cateCollectionView;


@property (strong, nonatomic) UICollectionView *collectionView;
//数据源
@property (nonatomic, strong)NSArray *dataArray;
//图书
@property (nonatomic, strong)BookListPageModel *bookModel;

@property (strong, nonatomic) NSArray<XYClassifyModel *> *classifyModelArray;


@end

@implementation MallBookViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self getNetData];
    [self getCateNetData];
    [self buildUI];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    self.collectionView.frame = self.view.bounds;
}

- (void)getNetData {
    __weak typeof(self) weakSelf = self;
    [CXDNetHelp getRequestWithURLString:@"http://wenqujingdian.com/index.php/Jiekou/getBookByPage/" parameters:@{@"pageIndex": @"1", @"pageSize": @"6"} success:^(id  _Nullable responseObject) {
        //        NSLog(@"%@",responseObject);
        self.bookModel = [BookListPageModel mj_objectWithKeyValues:responseObject];
        [weakSelf.collectionView reloadData];
    } failure:^(NSError * _Nullable error) {
        
    }];
}

- (void)getCateNetData {
//    [CXDNetHelp getRequestWithURLString:ClassifyURL parameters:nil success:^(id  _Nullable responseObject) {
//        _dataArray = [NSArray yy_modelArrayWithClass:[ClassifyModel class] json:responseObject];
////        self.cateCollectionView.height = 80 * (_dataArray.count / 2 + 1) + 50;
////        if (self.block) {
////            self.block(80 * (_dataArray.count / 3 + 1) + 50 + 500 + 20);
////        }
//        [self.collectionView reloadData];
//    } failure:^(NSError * _Nullable error) {
//
//    }];
    
    [CXDNetHelp getRequestWithURLString:@"http://www.wenqujingdian.com/index.php/jiekou/getBookClass" parameters:nil success:^(id  _Nullable responseObject) {
        
        self.classifyModelArray = [XYClassifyModel mj_objectArrayWithKeyValuesArray:responseObject];
        [self.collectionView reloadData];
    } failure:^(NSError * _Nullable error) {
        
    }];
}

- (void)buildUI {
    [self.view addSubview:self.searchView];
    [self.view addSubview:self.searchBtn];
    [self.view addSubview:self.collectionView];
}

#pragma mark - event response
- (void)searchBtnAction {
    BookSearchVC *sechVC = [[BookSearchVC alloc] init];
    [self.navigationController pushViewController:sechVC animated:YES];
}

- (void)moreBtnAction {
    BookMoreVC *moreVC = [[BookMoreVC alloc] init];
    [self.navigationController pushViewController:moreVC animated:YES];
}
#pragma mark - 懒加载
- (BookTypeSearchView *)searchView {
    if (!_searchView) {
        _searchView = [[BookTypeSearchView alloc] initWithFrame:CGRectMake(0, 10, kScreenWidth, 60)];
    }
    return _searchView;
}

- (UIButton *)searchBtn {
    if (!_searchBtn) {
        _searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _searchBtn.frame = CGRectMake(0, 0, kScreenWidth, 80);
        [_searchBtn addTarget:self action:@selector(searchBtnAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _searchBtn;
}

- (UICollectionView *)collectionView {
    if (_collectionView == nil) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = RGB(238, 238, 238);
        [_collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([BookCollectCell class]) bundle:nil] forCellWithReuseIdentifier:NSStringFromClass([BookCollectCell class])];
        [_collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([FooterCollectionReusableView class]) bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:NSStringFromClass([FooterCollectionReusableView class])];
        [_collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([MallBookHeaderCollectionReusableView class]) bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:NSStringFromClass([MallBookHeaderCollectionReusableView class])];
        [self.collectionView registerClass:ClassifyHeaderView.class forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"ClassifyHeaderView"];
    }
    return _collectionView;
}

- (UICollectionView *)showCollectionView {
    if (!_showCollectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.itemSize = CGSizeMake((kScreenWidth ) / 3, 150);
        layout.minimumLineSpacing = 0;
        layout.minimumInteritemSpacing = 0;
        layout.footerReferenceSize = CGSizeMake(kScreenWidth, 65);
        layout.headerReferenceSize = CGSizeMake(kScreenWidth, 30);
        _showCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, self.searchView.bottom + 10, kScreenWidth, 395) collectionViewLayout:layout];
        _showCollectionView.delegate = self;
        _showCollectionView.dataSource = self;
        _showCollectionView.backgroundColor = RGB(238, 238, 238);
        _showCollectionView.showsVerticalScrollIndicator = NO;
        [_showCollectionView registerNib:[UINib nibWithNibName:NSStringFromClass([BookCollectCell class]) bundle:nil] forCellWithReuseIdentifier:NSStringFromClass([BookCollectCell class])];
        [_showCollectionView registerNib:[UINib nibWithNibName:NSStringFromClass([FooterCollectionReusableView class]) bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:NSStringFromClass([FooterCollectionReusableView class])];
        [_showCollectionView registerNib:[UINib nibWithNibName:NSStringFromClass([MallBookHeaderCollectionReusableView class]) bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:NSStringFromClass([MallBookHeaderCollectionReusableView class])];
    }
    return _showCollectionView;
}

- (UICollectionView *)cateCollectionView {
    if (!_cateCollectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.itemSize = CGSizeMake((kScreenWidth ) / 3, 80);
        layout.minimumLineSpacing = 0;
        layout.minimumInteritemSpacing = 0;
        layout.headerReferenceSize = CGSizeMake(kScreenWidth, 50);
        _cateCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, self.showCollectionView.bottom + 10, kScreenWidth, 210) collectionViewLayout:layout];
        _cateCollectionView.delegate = self;
        _cateCollectionView.dataSource = self;
        _cateCollectionView.backgroundColor = RGB(238, 238, 238);
        _cateCollectionView.showsVerticalScrollIndicator = NO;
        [_cateCollectionView registerNib:[UINib nibWithNibName:NSStringFromClass([BookClassifyCollectionCell class]) bundle:nil] forCellWithReuseIdentifier:NSStringFromClass([BookClassifyCollectionCell class])];
        [_cateCollectionView registerNib:[UINib nibWithNibName:NSStringFromClass([CateCenterCollectionReusableView class]) bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:NSStringFromClass([CateCenterCollectionReusableView class])];
    }
    return _cateCollectionView;
}

#pragma mark - UICollectionViewDelegate,UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1 + self.classifyModelArray.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (section == 0) {
        return self.bookModel.list.count > 6? 6 : self.bookModel.list.count;
    }
    return self.classifyModelArray[section - 1].childs.count > 3? 3: self.classifyModelArray[section - 1].childs.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    BookCollectCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([BookCollectCell class]) forIndexPath:indexPath];
    if (indexPath.section == 0) {
        cell.backView.hidden = YES;
        BookListPageItemModel *tempModel = self.bookModel.list[indexPath.item];
        [cell.bookImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",RootHomeURL,tempModel.spic]]];
        cell.nameLabel.text = tempModel.news_tit;
        return cell;
    } else {
        cell.backView.hidden = YES;
        BookListPageItemModel *tempModel = self.classifyModelArray[indexPath.section - 1].childs[indexPath.item];
        [cell.bookImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",RootHomeURL,tempModel.spic]]];
        cell.nameLabel.text = tempModel.news_tit;
        return cell;
    }
//    BookClassifyCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([BookClassifyCollectionCell class]) forIndexPath:indexPath];
//    ClassifyModel *tempModel = _dataArray[indexPath.item];
//    cell.nameLaebl.text = tempModel.name;
//    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (![CXDHelper getUserLoginStatus] && [NSUserDefaults.standardUserDefaults boolForKey:K_NeedLogin]) {
            LoginViewController *loginVC = [[LoginViewController alloc] init];
            [self.navigationController pushViewController:loginVC animated:YES];
            [CXDNoticeView showNoticeViewWithString:@"请先进行登陆"];
            return;
        }
        BookDetailShowViewController *detailVC = [[BookDetailShowViewController alloc] init];
        BookListPageItemModel *tempModel = self.bookModel.list[indexPath.item];
        detailVC.navigationItem.title = tempModel.news_tit;
        detailVC.bookId = tempModel.bookID == nil? tempModel.id: tempModel.bookID;
        [self.navigationController pushViewController:detailVC animated:YES];
    }else {
//        BookCateVC *cateVC = [[BookCateVC alloc] init];
//        XYClassifyModel *tempModel = self.classifyModelArray[indexPath.section - 1];
//        cateVC.cateId = tempModel.id;
//        cateVC.navigationItem.title = tempModel.name;
//        [self.navigationController pushViewController:cateVC animated:YES];
        BookDetailShowViewController *detailVC = [[BookDetailShowViewController alloc] init];
        BookListPageItemModel *tempModel = self.classifyModelArray[indexPath.section - 1].childs[indexPath.item];
        detailVC.navigationItem.title = tempModel.news_tit;
        detailVC.bookId = tempModel.bookID == nil? tempModel.id: tempModel.bookID;
        [self.navigationController pushViewController:detailVC animated:YES];
    }
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if ([kind isEqualToString:UICollectionElementKindSectionFooter]) {
            FooterCollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:NSStringFromClass([FooterCollectionReusableView class]) forIndexPath:indexPath];
            [view.moreBtn addTarget:self action:@selector(moreBtnAction) forControlEvents:UIControlEventTouchUpInside];
            return view;
        } else {
            MallBookHeaderCollectionReusableView *header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:NSStringFromClass([MallBookHeaderCollectionReusableView class]) forIndexPath:indexPath];
            header.nameLabel.text = [NSString stringWithFormat:@"共%@部作品",self.bookModel.total == nil? @"" : self.bookModel.total];
            NSRange ran = NSMakeRange(1, header.nameLabel.text.length - 4);
            NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:header.nameLabel.text];
            [string addAttributes:@{NSForegroundColorAttributeName:MainGreenColor} range:ran];
            header.nameLabel.attributedText = string;
            return header;
        }
    } else {
        if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
            ClassifyHeaderView *header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"ClassifyHeaderView" forIndexPath:indexPath];
            header.classifyTitle = self.classifyModelArray[indexPath.section - 1].name;
            header.section = indexPath.section - 1;
            header.delegate = self;
            return header;
        }
    }
//    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
//        CateCenterCollectionReusableView *header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:NSStringFromClass([CateCenterCollectionReusableView class]) forIndexPath:indexPath];
//        return header;
//    }
    return nil;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    
    if (section == 0) {
        return 5;
    }
    return 0;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    
    if (section == 0) {
        return 5;
    }
    return 0;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        return CGSizeMake((kScreenWidth - 10) / 3, 150);
    }
    return CGSizeMake((kScreenWidth - 10) / 3, 150);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    
    if (section == 0) {
        return CGSizeMake(kScreenWidth, 30);
    } else {
        return CGSizeMake(kScreenWidth, 45);
    }
    return CGSizeZero;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
    
    if (section == 0) {
        return CGSizeMake(kScreenWidth, 65);
    }
    return CGSizeZero;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    
//    if (section != 0) {
//        return UIEdgeInsetsMake(5, 0, 5, 0);
//    }
    return UIEdgeInsetsZero;
}

#pragma mark - ClassifyHeaderViewDelegate
- (void)classifyHeaderView:(ClassifyHeaderView *)headerView moreBtnDidClick:(UIButton *)button atSection:(NSInteger)section {
    
    BookMoreVC *vc = [[BookMoreVC alloc] init];
    XYClassifyModel *tempModel = self.classifyModelArray[section];
    vc.classifyId = tempModel.id;
    vc.navigationItem.title = tempModel.name;
    [self.navigationController pushViewController:vc animated:YES];

}


@end
